import { lazy } from 'react'
import { isArray } from '@/utils/utils'
import LazyLoad from '@/utils/lazyLoad.tsx'
const AuthProvider = lazy(() => import('@/AuthProvider'))
const Login = lazy(() => import('@/pages/login'))
const Layout = lazy(() => import('@/layout'))
const ErrorPage = lazy(() => import('@/pages/error-page'))

type Auth = {
  resource: string | RegExp
  actions?: string[]
}

export interface AuthParams {
  requiredPermissions?: Array<Auth>
  oneOfPerm?: boolean
}
export type IRoute = AuthParams & {
  name: string
  key: string
  path?: string
  index?: boolean
  element?: JSX.Element
  meta?: Record<string, any>
  // 当前页是否展示面包屑
  breadcrumb?: boolean
  children?: IRoute[]
  // 当前路由是否渲染菜单项，为 true 的话不会在菜单中显示，但可通过路由地址访问。
  ignore?: boolean
}
const routes = [
  {
    path: '/login',
    element: <Login />
  },
  {
    path: '/',
    element: (
      <AuthProvider>
        <Layout />
      </AuthProvider>
    ),

    children: [] as IRoute[]
  },
  {
    path: '*',
    element: <ErrorPage />
  }
]

export const asyncRoutes: IRoute[] = [
  {
    name: 'menu.dashboard',
    key: 'dashboard',
    children: [
      {
        name: 'menu.dashboard.workplace',
        key: 'dashboard/workplace',
        meta: {
          title: '1'
        }
      },
      {
        name: 'menu.dashboard.monitor',
        key: 'dashboard/monitor',
        requiredPermissions: [{ resource: 'menu.dashboard.monitor', actions: ['write'] }]
      }
    ]
  }
]

function getFlattenRoutes(routes: IRoute[]): IRoute[] {
  const res: IRoute[] = []
  function travel(_routes: IRoute[]) {
    _routes.forEach((route: IRoute) => {
      const visibleChildren = (route.children || []).filter((child) => !child.ignore)
      if (route.key && (!route.children || !visibleChildren.length)) {
        try {
          //组件地址
          // const URL = `../pages/${route.key}/index.tsx`
          // const Module = lazy(viteModule[`${URL}`] as any)
          route.element = LazyLoad(route.key)
          if (!route.index) route.path = route.key

          res.push(route)
        } catch (e) {
          console.error(e)
        }
      }

      if (isArray(route.children) && route.children?.length) {
        travel(route.children)
      }
    })
  }
  travel(routes)
  return res
}
export const generatePermission = (role: string) => {
  const actions = role === 'admin' ? ['*'] : ['read']
  const result: Record<string, string[]> = {}
  asyncRoutes.forEach((item) => {
    if (item.children) {
      item.children.forEach((child) => {
        result[child.name] = actions
      })
    }
  })
  return result
}
routes[1].children = getFlattenRoutes(asyncRoutes)
export default routes
